
#include "common.c"
#include <pthread.h>

#define MAX_LINE 1024

char process_char(char c) {
	if (c >= 'a' && c <= 'z') {
		return c - 32;
	} else if (c >= 'A' && c <= 'Z') {
		return c + 32;
	}
	return c;
}

void *thread_process(void *arg) {
	int fd = *((int *) arg);
	char outbuf[MAX_LINE + 1];
	size_t outbuf_used = 0;
    ssize_t result;

	for (;;) {
		char ch;
		result = read(fd, &ch, 1);
		if (result == 0) {
			break;
		} else if (result == -1) {
			perror("read error");
			break;
		}

		if (outbuf_used < sizeof(outbuf)) {
            outbuf[outbuf_used++] = process_char(ch);
        }

        if (ch == '\n') {
            write(fd, outbuf, outbuf_used);
            outbuf_used = 0;
            continue;
        }
	}
}


int main() {
	struct sockaddr_in client_sockaddr;
	int sin_size;
	int listener_fd = tcp_server_listen(SERVPORT);
	
	pthread_t tid;

	for (;;) {
		int fd = accept(listener_fd, (struct sockaddr *) &client_sockaddr, &sin_size);
		if (fd < 0) {
			perror("accept failed");
			exit(1);
		}
		
		printf("create a thread for socket fd = %d\n", fd);
		
		pthread_create(&tid, NULL, thread_process, &fd);	
	}

	return 0;
}
